from aip import AipOcr
import os, shutil
import fnmatch
import Zip

# """ 韩泽旭的 APPID AK SK """
# APP_ID = '25205305'
# API_KEY = 'iqBV0uXMxR4qnekeORIqQmUN'
# SECRET_KEY = 'AomX8ENhERe7jGzOI6aj5LFiujpdFhvh'

APP_ID = '25245042'
API_KEY = 'y1GoMvXLTGNKwrG2Aip5x6pE'
SECRET_KEY = 'vkdKjGNAo9sFKsT2WEqmklGp3yEZGHUT'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

""" 读取图片 """


def fun(file_name,time,i):

    # 源文件
    src_file = Zip.src_dicname + i + '/' + file_name
    # 目标文件
    target = Zip.target_dicname + i
    # 错误文件
    wrong = Zip.wrong + i
    # 错误日志
    log = Zip.log + i + '/wrong.txt'


    if not os.path.exists(Zip.target_dicname + i):
        os.makedirs(Zip.target_dicname + i)  # 创建路径

    try:
        image = open(src_file, 'rb').read()
        options = {}
        options["detect_direction"] = "true"

        result = {}
        if time < 980:
            result = client.basicAccurate(image, options)
        else:
            result = client.basicGeneral(image, options)
        words = result['words_result']

        new_txt_name = ''
        if fnmatch.fnmatch(file_name, '*.jpeg') or fnmatch.fnmatch(file_name, '*.JPEG'):
            new_txt_name = file_name[:-5] + '.txt'
        else:
            new_txt_name = file_name[:-4] + '.txt'
        word_to_txt = target + "/" + new_txt_name

        with open(word_to_txt, "a") as file:  # 只需要将之前的”w"改为“a"即可，代表追加内容
            for line in words:
                file.write(line['words'] + "\n")

    except BaseException as e:
        if not os.path.exists(Zip.wrong + i):
            os.makedirs(Zip.wrong + i)  # 创建路径
        shutil.move(src_file, wrong + "/")
        with open(log, "a") as file:  # "a"代表追加内容
            file.write(file_name + " " + repr(e) + "\n")
